package com.editor.smsmanager;

import android.annotation.SuppressLint;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.telephony.SubscriptionInfo;
import android.telephony.SubscriptionManager;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.editor.smsmanager.utils.MyLog;

import java.util.List;
import java.util.Random;
import java.util.UUID;

public class SendSmsActivity extends AppCompatActivity {

    public static final String SENT_SMS_ACTION = "SENT_SMS_ACTION";
    public static final String DELIVERED_SMS_ACTION = "DELIVERED_SMS_ACTION";
    public static final String EXTRA_SEND_ID = "EXTRA_SEND_ID";

    TextView simOneEdit;
    TextView simTwoEdit;
    TextView destNumber;

    ProgressDialog progressDialog;

    String per[] = {"android.permission.READ_PHONE_STATE", "android.permission.READ_PRIVILEGED_PHONE_STATE"};

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_send_sms);

        registerReceiver();

        destNumber = findViewById(R.id.dest_number_edit);
        simOneEdit = findViewById(R.id.sms_1_edit);
        simTwoEdit = findViewById(R.id.sms_2_edit);

        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("Please wait...");


        findViewById(R.id.sms_1_send).setOnClickListener(v->sendSms(destNumber.getText().toString(), getSubscriptionSize(0), simOneEdit.getText().toString()));
        findViewById(R.id.sms_2_send).setOnClickListener(v->sendSms(destNumber.getText().toString(), getSubscriptionSize(1), simTwoEdit.getText().toString()));
        requestPermissions(per, 100);
    }

    @Override
    protected void onResume() {
        super.onResume();


    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        getSubscriptionSize(0);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        unregisterReceiver(sendSmsReceiver);
    }

    @SuppressLint("MissingPermission")
    private int getSubscriptionSize(int pos){
        int subId = -1;

        SubscriptionManager subscriptionManager = SubscriptionManager.from(this);
         List<SubscriptionInfo> subscriptionInfoList = subscriptionManager.getActiveSubscriptionInfoList();

         if(subscriptionInfoList == null){
            MyLog.E("subscriptionInfoList is NULL");
         } else {
             for (SubscriptionInfo subscriptionInfo : subscriptionInfoList) {
                 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                     MyLog.D("subscriptionInfo SubscriptionId=" + subscriptionInfo.getSubscriptionId() + ",IccId=" + subscriptionInfo.getIccId()
                             + ",CarrierId=" + subscriptionInfo.getCarrierId() + ",getDisplayName=" + subscriptionInfo.getDisplayName()
                             + ",getDataRoaming=" + subscriptionInfo.getDataRoaming()
                             + ",Number=" + subscriptionInfo.getNumber() + ",SimSlotIndex=" + subscriptionInfo.getSimSlotIndex());
                 } else {
                     MyLog.D("subscriptionInfo SubscriptionId=" + subscriptionInfo.getSubscriptionId() + ",IccId=" + subscriptionInfo.getIccId()
                             + ",Number=" + subscriptionInfo.getNumber() + ",SimSlotIndex=" + subscriptionInfo.getSimSlotIndex());
                 }

                 showSubscriptionInfo(subscriptionInfo);
             }

             if(pos < subscriptionInfoList.size()){
                 subId = subscriptionInfoList.get(pos).getSubscriptionId();
             }
         }

        return subId;
    }

    private void sendSms(String dest, int subId, String text){
        if(dest == null || dest.length() < 3) return;
        if(subId < 0) return;
        if(TextUtils.isEmpty(text)) return;

        Random random = new Random();
        String smsSendId = UUID.randomUUID().toString();

        Intent sentIntent = new Intent(SENT_SMS_ACTION);
        sentIntent.putExtra(EXTRA_SEND_ID, smsSendId);
        PendingIntent sentPI = PendingIntent.getBroadcast(this, random.nextInt(), sentIntent, PendingIntent.FLAG_UPDATE_CURRENT);


        SmsManager smsManager = SmsManager.getSmsManagerForSubscriptionId(subId);
        smsManager.sendTextMessage(dest, null, text, sentPI, null);

        progressDialog.show();
    }

    private void registerReceiver(){
        registerReceiver(sendSmsReceiver, new IntentFilter(SENT_SMS_ACTION));
    }

    private BroadcastReceiver sendSmsReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            MyLog.D("SENT_SMS_ACTION smsSendId="+intent.getStringExtra(EXTRA_SEND_ID));
            if(progressDialog.isShowing()) progressDialog.dismiss();
        }
    };

    private void showSubscriptionInfo(SubscriptionInfo subscriptionInfo){
        int res[] = {R.id.sim_bitmap_0, R.id.sim_bitmap_1};

        Bitmap bitmap = subscriptionInfo.createIconBitmap(this);

        ImageView imageView = findViewById(res[subscriptionInfo.getSimSlotIndex()]);
        imageView.setImageBitmap(bitmap);
    }

}
